package com.itheima.factory;

import com.itheima.utils.sqlSessionUtiles;
import org.apache.ibatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class DaoInstanceFactory {
    /**
     *
     * @param interfaceClass Dao接口Class
     * @param <T> 返回Dao代理对象
     * @return
     */
    public static <T> T getMapper(Class<T> interfaceClass){//Student.Dao
    //获取SqlSession
        SqlSession sqlSession = sqlSessionUtiles.getSqlSession();
        //2.使用框架生成代理对象
        T mapper = sqlSession.getMapper(interfaceClass);
        //3.对框架生成代理对象方法进行增强,让其支持事务
        T Proxy_mapper=(T) Proxy.newProxyInstance(mapper.getClass().getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object value = null;
                try {
                    value = method.invoke(mapper, args);
                    System.out.println("事务增强了");
                    //成功,手动提交事务
                    sqlSession.commit();
                } catch (IllegalAccessException e) {
                    //失败.事务回滚
                    System.out.println("事务增强失败了");
                    sqlSession.rollback();
                    e.printStackTrace();
                } finally {
                    //释放资源
                    sqlSession.close();
                }
                return value;
            }
        });
        return Proxy_mapper;
    }
}
